package org.smth.search.fetcher.impl;

import com.google.inject.Inject;

import org.smth.search.config.FetcherConfig;
import org.smth.search.config.SiteConfig;
import org.smth.search.fetcher.*;
import org.smth.search.parser.PostItemParser;
import org.smth.search.parser.PostParser;
import org.smth.search.types.BoardInfo;
import org.smth.search.types.Post;
import org.smth.search.types.PostItem;

public class BoardFetcherImpl implements BoardFetcher {

	@Inject
	private FetcherConfig fetcherConfig;

	@Inject
	private PageFetcher pageFetcher;

	@Inject
	private PostItemParser postItemParser;

	@Inject
	private SiteConfig siteConfig;

	@Inject
	private PostParser postParser;

	private String board;

	public synchronized String getBoard() {
		if (board == null) {
			board = fetcherConfig.getNextBoard();
		}
		return board;
	}

	private int currentPage;

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	private String contentCache;

	private String fetchContent(String url) {
		String content = pageFetcher.fetchPage(url);
		this.contentCache = content;
		return content;
	}

	private BoardInfo boardInfo;

	public synchronized int getPageCount() {
		if (boardInfo != null) {
			return boardInfo.getPageCount();
		}
		String board = getBoard();
		String url = siteConfig.getBoardConfig().getBoardUrl(board);
		String content = fetchContent(url);
		boardInfo = postItemParser.getPageCount(content);
		int size = boardInfo.getPageCount();
		this.setCurrentPage(size);
		return size;
	}

	public PostItem[] getPostItems(int page, boolean withTop) {
		assert page > 0 && page <= this.getPageCount();
		if (page == this.currentPage) {
			return postItemParser.parsePostItems(contentCache, withTop);
		} else {
			String board = getBoard();
			String url = siteConfig.getBoardConfig().getBoardUrl(board, page);
			String content = fetchContent(url);
			this.setCurrentPage(page);
			return postItemParser.parsePostItems(content, withTop);
		}
	}

	public Post getPost(PostItem item) {
		assert item != null;
		String boardId = boardInfo.getBoardId();
		int postId = item.getId();
		String url = siteConfig.getBoardConfig().getPostUrl(boardId, postId);
		String content = pageFetcher.fetchPage(url);
		return postParser.parsePost(content);
	}
}
